const wxapi = require("../../utils/wxapi");
import { Util } from "../../utils/util";
import { API_SNZO_FILE_URL, API_SNZO_URL } from "../../utils/wxapi";

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    isUnitUser: false,
    seachTypeOfData: [{ label: '艺术品名称', value: 'worksName' }, { label: '作者', value: 'standby2' }],
    seachTypeIndex: 0,
    seachPlaceholderText: '请输入艺术品名称',
    exchangeStatusOfData: [{ label: '全部', status: null }, { label: '交易中', status: 1 }, { label: '委托中', status: 7 }, { label: '交易完成', status: 5 }],
    exchangeStatusIndex: 0,
    typeOfData: null,
    worksTypeIndex: 0,
    listOfData: [],
    worksTypeOfData: null,
    snzoImgUrl: API_SNZO_FILE_URL,
    bodyParams: {
      worksStatus: 1,
      worksName: '',
      standby1: '',
      standby2: '',
      worksType: '',
      standby5: 2,
      standby12: '',
      softDelete: 1,
    },
    pageParams: { pageNum: 1, pageSize: 10 },
    total: 0,
    scrollTop: 0,
    canScroll: false,
    showEntrust: false,
    entrustInfo: null,
    isTriggered: false,
    buyType: null,
    unfole: false,
    priceLowValue: null,
    priceHighValue: null,
    worksInputValue: null
  },

  /**
   * 获取艺术品类型
   */
  getWorksType() {
    wxapi.getStNumWorksType({ standby3: 1 }).then(res => {
      if (res.status === 200) {
        const result = res.data.filter(item => {
          item.typeName = item.typeName.slice(0, 2);
          return item;
        }).reverse();
        this.setData({
          worksTypeOfData: result,
          typeOfData: [{ typeName: '全部作品', id: 0 }, ...result]
        })
      }
    })
  },

  /**
   * 获取艺术品列表
   */
  getWorksList() {
    wx.showLoading({
      title: '加载中',
    })
    const body = Util.trimNulls(this.data.bodyParams);
    const params = Util.trimNulls(this.data.pageParams);
    let pageParams = '';
    for (const key in params) {
      if (Object.hasOwnProperty.call(params, key)) {
        const value = params[key];
        pageParams += `&${key}=${value}`
      }
    }
    wxapi.selectDealPage(body, pageParams).then(res => {
      wx.hideLoading();
      this.setData({
        isTriggered: false
      })
      if (res.status === 200) {
        if (this.data.pageParams.pageNum === 1) {
          this.data.listOfData = [];
          this.setData({
            scrollTop: 0
          })
        }
        const listOfData = res.data.data;
        const newData = this.data.listOfData.concat(listOfData);
        this.setData({
          listOfData: newData,
          total: res.data.total,
          canScroll: true
        })
      }
    })
  },

  /**
   * 展开/收缩 价格区间
   */
  chooseUnfole() {
    this.setData({
      unfole: !this.data.unfole
    })
  },

  /**
   * 搜索类型
   * @param {*} e 
   */
  seachTypeChange(e) {
    const seachPlaceholderText = e.detail.value == 0 ? '请输入艺术品名称' : '请输入艺术品作者';
    this.setData({
      seachTypeIndex: e.detail.value,
      seachPlaceholderText,
      worksInputValue: null
    })
  },

  /**
   * 输入搜索词
   * @param {*} e 
   */
  worksKeyInput(e) {
    const value = e.detail.value;
    this.setData({
      worksInputValue: value
    })
  },
  /**
   * 艺术品类型
   * @param {*} e 
   */
  worksTypeChange(e) {
    this.setData({
      worksTypeIndex: e.detail.value
    })
    const value = this.data.typeOfData[this.data.worksTypeIndex].id;
    if (value === 0) {
      this.data.bodyParams.worksType = '';
    } else {
      this.data.bodyParams.worksType = value;
    }
    this.data.pageParams.pageNum = 1;
    this.getWorksList();
  },

  /**
   * 按艺术品名称或作者 搜索作品
   * @param {*} e 
   */
  seachWorksByInput(e) {
    // const value = e.detail.value;
    const seachType = this.data.seachTypeOfData[this.data.seachTypeIndex].value;
    if (seachType === 'worksName') {
      this.data.bodyParams.standby2 = '';
      this.data.bodyParams.worksName = this.data.worksInputValue;
    } else if (seachType === 'standby2') {
      this.data.bodyParams.worksName = '';
      this.data.bodyParams.standby2 = this.data.worksInputValue;
    }
    this.data.pageParams.pageNum = 1;
    this.getWorksList();
  },

  /**
   * 按交易状态搜索作品
   * @param {*} e 
   */
  exchangeStatusChange(e) {
    const value = e.detail.value;
    this.setData({
      exchangeStatusIndex: value
    })
    this.data.bodyParams.standby12 = this.data.exchangeStatusOfData[value].status;
    this.data.pageParams.pageNum = 1;
    this.getWorksList();
  },

  /**
   * 输入价格
   * @param {*} e 
   */
  priceKeyInput(e) {
    const value = e.detail.value;
    const priceType = e.currentTarget.dataset.priceType;
    const regex = /^[1-9]\d*$/;
    if (!isNaN(+value) && regex.test(value)) {
      if (priceType === 'low') {
        this.data.pageParams.lowMoney = value;
        this.setData({
          priceLowValue: value
        })
      } else if (priceType === 'high') {
        this.data.pageParams.highMoney = value;
        this.setData({
          priceHighValue: value
        })
      }
    } else {
      if (priceType === 'low') {
        this.data.pageParams.lowMoney = value;
        this.setData({
          priceLowValue: null
        })
      } else if (priceType === 'high') {
        this.data.pageParams.highMoney = value;
        this.setData({
          priceHighValue: null
        })
      }
    }
  },

  /**
   * 按价格区间搜索
   * @param {*} e 
   */
  seachWorksByPrice() {
    this.data.pageParams.pageNum = 1;
    this.getWorksList();
    this.setData({
      unfole: false,
      pageParams: this.data.pageParams
    })
  },

  /**
   * 关闭蒙板
   */
  closeUnfole() {
    this.setData({
      unfole: false
    })
  },

  /**
   * 预览艺术品
   * @param {*} e 
   */
  previewImage(e) {
    const worksItem = e.currentTarget.dataset.worksItem;
    wx.previewMedia({
      sources: [
        {
          url: this.data.snzoImgUrl + worksItem.worksPhoto,
          type: 'image'
        }
      ],
    })
  },

  /**
   * 校验用户类别
   * status 200 集团用户 status 400 个人用户
   */
  checkUserType() {
    wxapi.selectUnitUserByStk({ stk: app.globalData.userInfo.cardNo }).then(res => {
      if (res.status === 200) {
        this.setData({
          isUnitUser: true
        })
      } else if (res.status === 400) {
        this.setData({
          isUnitUser: false
        })
      }
    })
  },

  /**
   * 滑到最底部加载 获取分页数据
   */
  scrollToLower() {
    if (this.data.listOfData.length === this.data.total) {
      return;
    }
    this.setData({
      canScroll: false
    })
    this.data.pageParams.pageNum++
    setTimeout(() => {
      this.getWorksList();
    }, 1000);
  },

  /**
   * 下拉刷新
   */
  refresherToLoad() {
    this.data.pageParams.pageNum = 1;
    this.getWorksList();
  },

  /**
   * 购买商品
   */
  buyWorks(e) {
    if (this.isUnitUser) {
      wx.showModal({
        title: '提示信息',
        content: '您是集团用户，无法购买商品。',
        showCancel: true
      })
      return;
    } else if (!app.globalData.token) {
      wx.showModal({
        title: '提示信息',
        content: res.message,
        confirmText: '登录',
        complete: (res) => {
          app.globalData.userInfo = null;
          app.globalData.token = null;
          wx.removeStorage({
            key: 'userInfo',
          })
          wx.removeStorage({
            key: 'token',
          })
          if (res.cancel) {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        }
      })
      return;
    } else {
      const worksIndex = e.currentTarget.dataset.worksIndex;
      const worksItem = this.data.listOfData[worksIndex];
      wx.navigateTo({
        url: '/pages/shopDetail/shopDetail',
        success: (res) => {
          res.eventChannel.emit('worksMsg', { worksItemId: worksItem.id, worksTypeOfData: this.data.worksTypeOfData });
        }
      })
    }
  },

  /**
   * 委托
   * @param {*} e 
   */
  entrustBuyWorks(e) {
    const entrustMsg = e.currentTarget.dataset.worksInfo;
    const buyType = e.currentTarget.dataset.buyType;
    this.data.buyType = buyType;
    this.setData({
      showEntrust: true,
      entrustInfo: entrustMsg
    })
  },

  /**
   * 取消弹窗
   */
  cancelPopup() {
    this.setData({
      showEntrust: false,
      entrustInfo: null
    })
  },

  /**
   * 确定委托
   * @param {*} e 
   */
  confirmEntrust(e) {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    const entrustInfo = e.detail.entrustInfo;
    if (!entrustInfo.expectPrice) {
      wx.showModal({
        title: '提示信息',
        content: '请填写意向价格',
        showCancel: false
      })
      return;
    }
    if (this.data.buyType === 'entrust') {
      this.entrustBeforeVerfity(entrustInfo);
    } else if (this.data.buyType === 'purpose') {
      this.purposeBuyWorks(entrustInfo);
    }
  },

  /**
   * 意向购买
   * @param {*} entrustInfo 
   */
  purposeBuyWorks(entrustInfo) {
    const bodyParams = Object.assign({ stk: this.data.userInfo.cardNo, entrustType: 1, item: 1 }, entrustInfo);
    wxapi.addPurpose(bodyParams).then(res => {
      if (res.status === 200) {
        wx.showToast({
          title: '意向购买成功',
          duration: 2000,
          success: () => {
            wx.navigateTo({
              url: '/pages/center/entrust/entrust',
            })
          }
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.msg,
          showCancel: false
        })
      }
    })
  },

  /**
   * 委托前校验
   * @param {*} entrustInfo 
   */
  entrustBeforeVerfity(entrustInfo) {
    const bodyParams = Object.assign({ stk: this.data.userInfo.cardNo, entrustType: 1, item: 1 }, entrustInfo);
    wxapi.entrustBeforeVerfity(bodyParams).then(res => {
      if (res.status === 200) {
        this.setData({
          isPaying: true
        })
        wx.showLoading({
          title: '支付中',
        })
        const openId = wx.getStorageSync('openId');
        if (openId) {
          // 委托购买
          this.payEntrust({ openId }, bodyParams);
        } else {
          wx.login({
            success: (res) => {
              if (res.code) {
                const jsCode = res.code;
                const headers = {
                  'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
                }
                wxapi.getMiniOpenId({ jsCode }, headers).then(res => {
                  if (res.code === 20000) {
                    if (res.data) {
                      wx.setStorageSync('openId', res.data);
                      // 委托购买
                      this.payEntrust({ openId: res.data }, bodyParams);
                    } else {
                      this.data.isHandle = false;
                      wx.hideLoading()
                      this.setData({
                        isPaySubmit: false
                      })
                      wx.showToast({
                        title: '获取openId失败',
                        icon: 'error'
                      })
                    }
                  } else {
                    this.data.isHandle = false;
                    wx.hideLoading();
                    wx.showModal({
                      title: '提示信息',
                      content: res.message,
                      showCancel: false
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: '登录失败',
                  icon: 'error',
                  success: () => {
                    this.setData({
                      isPaySubmit: false
                    })
                    wx.switchTab({
                      url: '/pages/index/index',
                    })
                  }
                })
              }
            },
          })
        }
      } else {
        this.data.isHandle = false;
        wx.showModal({
          title: '提示信息',
          content: res.msg,
          showCancel: false
        })
      }
    })
  },

  /**
   * 支付
   */
  payEntrust(params, bodyParams) {
    wxapi.entrustXcxPay(params, bodyParams).then(res => {
      if (res.status === 200) {
        wx.hideLoading();
        wx.requestPayment({
          nonceStr: res.data.nonceStr,
          package: res.data.packageValue,
          paySign: res.data.paySign,
          signType: res.data.signType,
          timeStamp: res.data.timeStamp,
          success: (res) => {
            this.data.isHandle = false;
            this.setData({
              showEntrust: false
            })
            wx.showToast({
              title: '购买成功',
              success: () => {
                wx.navigateTo({
                  url: '/pages/center/entrust/entrust',
                })
              }
            })
          },
          fail: (res) => {
            this.data.isHandle = false;
            this.setData({
              showEntrust: false
            })
            if (res.errMsg.indexOf('fail cancel') !== -1) {
              wx.showToast({
                title: '交易取消',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '订单数据异常',
                icon: 'error'
              })
            }
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (app.globalData.token) {
      this.getWorksType();
      this.getWorksList();
      this.checkUserType();
      this.setData({
        userInfo: app.globalData.userInfo
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    if (app.globalData.token) {
      this.data.worksInputValue = null;
      this.data.worksTypeIndex = 0;
      this.data.seachTypeIndex = 0;
      this.data.pageParams = { pageNum: 1, pageSize: 10 };
      this.data.bodyParams.worksName = null;
      this.data.bodyParams.standby2 = null;
      this.data.bodyParams.worksType = null;
      this.getWorksType();
      this.getWorksList();
      this.checkUserType();
      this.setData({
        userInfo: app.globalData.userInfo,
        unfole: false,
        worksInputValue: this.data.worksInputValue,
        worksTypeIndex: this.data.worksTypeIndex,
        seachTypeIndex: this.data.seachTypeIndex,
        pageParams: this.data.pageParams
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})